"""
Case Type   : merge_into
Case Name   : merge into全局临时表
Create At   : 2024/07/25
Owner       : songjing20
Description :
    1.创建全局临时表
    2.新开会话执行Merge语句，查询表
    3.清理环境
Expect      :
    1.创建表成功
    2.merge into成功，查询成功(2, 1)
    3.成功
History     :
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class MergeInto(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_mergeinto_0036'

    def test_mergeinto(self):
        text = '-----step1:创建全局临时表;expect:成功-----'
        self.log.info(text)
        res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;"
            f"create global temporary table {self.tb_name}(id int,name text);")
        self.log.info(res)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, res, f"执行失败:{text}")

        text = '-----step2:新开会话执行Merge语句，查询表;expect:成功,(2, 1)-----'
        self.log.info(text)
        sql_cmd = f'''merge into {self.tb_name} using sys_dummy on id = 2
        when not matched then insert values(2,'1') 
        when matched then update set name = '1';
        select * from {self.tb_name};'''
        res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(res)
        self.assertIn('MERGE 1', res, f"执行失败:{text}")
        self.assertIn(' 2 | 1\n(1 row)', res, f"执行失败:{text}")

    def tearDown(self):
        text = '--step3:清理环境;expect:成功-------'
        self.log.info(text)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name};")
        self.log.info(drop_res)
        self.assertEqual(self.constant.TABLE_DROP_SUCCESS, drop_res,
                         f"执行失败:{text}")
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
